package com.dddd.blog.blogcommon.advice;

import com.dddd.blog.blogcommon.annotation.ResponseResult;
import com.dddd.blog.blogcommon.pojo.Result;
import com.dddd.blog.blogcommon.utils.ResultUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 只有被ResponseResult修饰的控制器会被增强
 */
@ControllerAdvice(annotations = ResponseResult.class)
/**
 * 统一响应增强
 * @author 喵星球的大橘
 */
public class MyResponseHandlerAdvice implements ResponseBodyAdvice {

    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    /**
     * @param methodParameter
     * @param aClass
     * @return 此处如果返回false , 则不执行当前Advice的业务
     *
     * 是否请求包含了指定{ResponseResult}注解 标记，没有直接返回不需要重写返回体，
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(MediaType.APPLICATION_JSON.equals(selectedContentType) || MediaType.APPLICATION_JSON_UTF8.equals(selectedContentType)){
            // 判断响应的Content-Type为JSON格式的body

            if(body == null){
                return ResultUtils.success();
            }

            if(body instanceof Result){
                // 如果响应返回的对象为统一响应体，则直接返回body
                return body;
            }else{
                return ResultUtils.success(body);
            }
        }
        // 非JSON格式body直接返回即可
        return body;
    }
}
